package com.itheima.reggie.ctrl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.model.entity.Category;
import com.itheima.reggie.model.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.print.DocFlavor;
import java.util.List;

/**
 * @author zwx
 */
//@RUV(name = "对象映射器", techHighlights = "JSON解析为Java对象,Java对象生成JSON", labelJson = "Java,对象映射")
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> sava(@RequestBody Category category) {
        log.info("新增分类为：category{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分类 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize){
        log.info("page={},pagesize={}",page,pageSize);
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        //添加排序条件，按照Category表的sort大小进行排序
        wrapper.orderByAsc(Category::getSort);
        //进行分页查询。不需要返回，因为在里面会把查询到的值自动赋给pageInfo的records，total等
        categoryService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除分类——根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("删除分类，id为:{}",ids);

        categoryService.remove(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 据分类id修改分类名称、排序
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息为：category{}",category);
        categoryService.updateById(category);
        return R.success("分类信息修改成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加条件-根据type来查询
        wrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加条件-优先根据sort正序排序，sort相同时根据updatetime逆序排序（最近更新的排前面）
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //查询
        List<Category> list = categoryService.list(wrapper);

        return R.success(list);
    }
}
